import React from "react";
import { Component, ErrorInfo, ReactNode } from "react";

interface Props {
  children: ReactNode;
}
interface State {
  hasError: boolean;
}

export default class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false };

  static getDerivedStateFromError(_: Error): State {
    return { hasError: true };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error("全局错误:", error, info);
  }

  render() {
    return this.state.hasError ? (
      <div>应用发生错误，请刷新页面</div>
    ) : (
      this.props.children
    );
  }
}
